library(shiny)
library(wordcloud)
library (ggplot2)
library (reshape)
library(topicmodels)

load("data_k50.RData")


post <- posterior(TM)
K <- 50

# pre-processing for plot3
# TEEMADE OSAKAAL
#K <- 50
N <- ceiling(nrow(post$topics)/30)
m <- matrix(NA, nrow=N, ncol=K)
for(i in 1:N){
  sub <- post$topics[((i-1)*30 + 1):min((i*30), nrow(post$topics)), ]
  tmp <- colSums(sub)
  m[i, ] <- tmp/sum(tmp)
}

Terms <- terms(TM, 2)
terms2 <- apply(Terms, 2, function(x) paste(x, collapse=" "))
colnames(m) <- paste(1:K, terms2)
m <- data.frame(m)
m$time <- 1:(N)
#---plot3----

# Define server logic for random distribution application
shinyServer(function(input, output) {
  
  # Return the requested dataset
  datasetInput <- reactive({
    switch(input$dataset,
           "Horoskoop_K50" = rock)
  })
  
  
  # Generate a summary of the data
  output$summary <- renderPrint({
    doc1 <- post$topics[2, ]
    
    cat("J?rgmine kirjutis on segu j?rgmistest teemadest (top3 teemat): ")
    cat("<br>")
    col1 <- "rgba(228,26,28,0.5)"
    col2 <- "rgba(55,126,184,0.5)"
    col3 <- "rgba(77,175,74,0.5)"
    col_holder <- c("<span style='background-color:rgba(228,26,28,0.5)'>",
                    "<span style='background-color:rgba(55,126,184,0.5)'>",
                    "<span style='background-color:rgba(77,175,74,0.5)'>")
    top3_topic_ind <- order(doc1, decreasing=TRUE)[1:3]
    cat(paste(col_holder, "Teema: ",names(doc1)[top3_topic_ind], "</span>", "(", 
          round(doc1[top3_topic_ind]*100, 3), "%)"))
    cat("<br>")
    cat("<br>")
    
    # värvime
    words <- colnames(post$terms)
    doc2 <- data1[2]
    doc_words <- strsplit(doc2, " ")[[1]]
    tekst <- c()
    for(i in 1:length(doc_words)){
      wo <- doc_words[i]
      wo.orig <- wo
      wo <- tolower(wo)
      wo <- gsub("[.]", "", wo)
      wo <- gsub("[,]", "", wo)
      wo <- gsub("[?]", "", wo)
      wo <- gsub("[!]", "", wo)
      if(wo %in% words){
        ind <- which(words == wo)
        to <- which.max(post$terms[, ind])
        if(to %in% top3_topic_ind){
          col <- c(col1,col2,col3)[which(to==top3_topic_ind)]
          tekst <- c(tekst, "<span style='background-color:", col, "'>",
                     wo.orig, "</span>", "<sup>", to, "</sup> ")
        }else{
          tekst <- c(tekst, wo.orig, "<sup>", to, "</sup> ")
        }
        
      } else{
        tekst <- c(tekst, wo.orig)
      }
    }
    cat(tekst)
  })
  
  
  output$plot2 <- renderPlot({
    #par(mfrow=c(3, 5), mar=c(1,3,3,1))
    par(mfrow=c(10, 5))
    for(i in 1:50){
      top_index <- order(post$terms[i, ], decreasing=TRUE)[1:5]
      top <- post$terms[i, top_index]
      
      wordcloud(names(top), freq=top, rot.per=0.0, min.freq=0,
                random.order=FALSE, scale=c(1.9, 0.1))
      mtext(paste("Teema", i), side=3, line=3, font=2)
    }
  })
  
  output$plot3 <- renderPlot({
    
    m.melt <- melt(m, id=c("time"))
    
    p = ggplot(m.melt, aes(x=time, y=value, group=variable))
    #p = p + geom_line() + facet_wrap(~variable, ncol=5)
    p = p + geom_smooth(method="loess", size=1, color="black") + 
      facet_wrap(~variable, ncol=5)
    p = p + coord_cartesian(ylim=c(0, 0.1))
    print(p)
    
  })
  
  output$hot <- renderPlot({
    # HOT/COLD TOPICS
    slopes <- rep(NA, K)
    for(i in 1:K){
      model <- lm(y ~ time, data=data.frame(y=m[, i], time=m$time))
      slopes[i] <- coef(model)[2]
    }
    
    hot5 <- order(slopes, decreasing=TRUE)[1:5]
    m.melt.hot <- melt(m[, c(hot5, 51)], id=c("time"))
    p = ggplot(m.melt.hot, aes(x=time, y=value, group=variable))
    #p = p + geom_line() + facet_wrap(~variable, ncol=5)
    p = p + geom_smooth(method="loess", size=1, color="black") + 
      facet_wrap(~variable, ncol=5)
    p = p + coord_cartesian(ylim=c(0, 0.10))
    print(p)

  })
  
  output$cold <- renderPlot({
    # HOT/COLD TOPICS
    slopes <- rep(NA, K)
    for(i in 1:K){
      model <- lm(y ~ time, data=data.frame(y=m[, i], time=m$time))
      slopes[i] <- coef(model)[2]
    }
    
    cold5 <- order(slopes, decreasing=FALSE)[1:5]
    m.melt.cold <- melt(m[, c(cold5, 51)], id=c("time"))
    p = ggplot(m.melt.cold, aes(x=time, y=value, group=variable))
    p = p + geom_smooth(method="loess", size=1, color="black") + 
      facet_wrap(~variable, ncol=5)
    p = p + coord_cartesian(ylim=c(0, 0.10))
    print(p)
  })
  
})
